<template>
  <div class="region-analysis-form">
    <el-form :model="formData" @submit.prevent="handleSubmit">
      <el-form-item label="行业名称" required>
        <el-autocomplete
          v-model="formData.industryName"
          :fetch-suggestions="queryIndustries"
          placeholder="请输入行业名称"
          :trigger-on-focus="true"
          clearable
          class="input-with-select"
          value-key="name"
          @select="handleSelect"
        >
          <template #default="{ item }">
            <div class="suggestion-item">
              {{ item.name }}
            </div>
          </template>
        </el-autocomplete>
      </el-form-item>

      <el-form-item>
        <el-button 
          type="primary" 
          @click="handleSubmit"
          :loading="loading"
          :disabled="!formData.industryName"
        >
          <el-icon><Search /></el-icon>
          查询分析
        </el-button>
      </el-form-item>

      <el-alert
        v-if="formData.industryName"
        type="info"
        show-icon
        :closable="false"
      >
        将分析 {{ formData.industryName }} 行业在各区域的分布情况
      </el-alert>
    </el-form>
  </div>
</template>

<script>
import { ref, reactive } from 'vue';
import { Search } from '@element-plus/icons-vue';
import { searchIndustries } from '@/api/graphAnalysis';

export default {
  name: 'RegionAnalysisForm',
  components: {
    Search
  },
  props: {
    loading: {
      type: Boolean,
      default: false
    }
  },
  emits: ['query'],
  setup(props, { emit }) {
    const formData = reactive({
      industryName: '',
      industryId: null
    });

    const queryIndustries = async (queryString, cb) => {
      try {
        const response = await searchIndustries(queryString);
        cb(response.data || []);
      } catch (error) {
        console.error('查询行业失败:', error);
        cb([]);
      }
    };

    const handleSelect = (item) => {
      formData.industryId = item.id;
      formData.industryName = item.name;
    };

    const handleSubmit = () => {
      if (!formData.industryName) return;
      
      emit('query', {
        industryId: formData.industryId,
        industryName: formData.industryName
      });
    };

    return {
      formData,
      queryIndustries,
      handleSelect,
      handleSubmit
    };
  }
};
</script>

<style scoped>
.region-analysis-form {
  padding: 20px;
}

.input-with-select {
  width: 100%;
}

.suggestion-item {
  padding: 8px 12px;
}

:deep(.el-alert) {
  margin-top: 16px;
}

:deep(.el-form-item:last-child) {
  margin-bottom: 0;
}

:deep(.el-button) {
  width: 100%;
  display: flex;
  align-items: center;
  justify-content: center;
  gap: 8px;
}
</style> 